package com.wframe.project.jnd.controller;

import java.io.IOException;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
import com.aliyun.oss.model.PutObjectResult;
import com.frame.database.JdataBean;
import com.frame.util.DateConvert;
import com.wframe.framework.util.UploadUtil;
import com.wframe.project.former.dataservices.upload.UploadService;
import com.wframe.project.jnd.extinterface.oss.AliyunOssConfig;
import com.wframe.project.jnd.extinterface.oss.AliyunOssUtils;

import net.sf.json.JSONObject;

/**
 * 统一文件上传服务(集成oss)
 * @author lenovo
 *
 */
@Controller
@RequestMapping("/upload")
public class UploadController {
	
	/**
	 * 获取oss签名
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "ossgetpolicy")
    public void ossgetpolicy(HttpServletRequest request,HttpServletResponse response) {
		String host = "http://"+AliyunOssConfig.getConfig().getBucket()+"."+AliyunOssConfig.getConfig().getEndpoint();
		String dir=request.getParameter("updir");if(dir==null)dir="";
		if(dir.endsWith("/"))dir=dir.substring(0, dir.length()-1);
		OSSClient client = new OSSClient(AliyunOssConfig.getConfig().getEndpoint(), AliyunOssConfig.getConfig().getAccessId(), AliyunOssConfig.getConfig().getAccessSecret());
        try {
        	long expireTime = AliyunOssConfig.getConfig().getExpireTime();
        	long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
            Date expiration = new Date(expireEndTime);
            PolicyConditions policyConds = new PolicyConditions();
            policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, 1048576000);
            policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, dir);
            if(StringUtils.isNotBlank(dir))dir+="/";
            String postPolicy = client.generatePostPolicy(expiration, policyConds);
            byte[] binaryData = postPolicy.getBytes("utf-8");
            String encodedPolicy = BinaryUtil.toBase64String(binaryData);
            String postSignature = client.calculatePostSignature(postPolicy);
            Map<String, String> respMap = new LinkedHashMap<String, String>();
            respMap.put("accessid", AliyunOssConfig.getConfig().getAccessId());
            respMap.put("policy", encodedPolicy);
            respMap.put("signature", postSignature);
            respMap.put("dir", dir);
            respMap.put("host", host);
            respMap.put("expire", String.valueOf(expireEndTime / 1000));
            Map<String,String> callbackMap=new LinkedHashMap<String,String>();
//            String basepath = request.getScheme()+"://"+request.getServerName()+(request.getServerPort()==80?"":":"+request.getServerPort())+request.getContextPath();
            callbackMap.put("callbackUrl", UploadUtil.getConfig().getUpserver()+"/upload/ossimgcallback");
            callbackMap.put("callbackBody", "filename=${object}&size=${size}&mimeType=${mimeType}&height=${imageInfo.height}&width=${imageInfo.width}");
            callbackMap.put("callbackBodyType", "application/x-www-form-urlencoded");
            String callback=JSONObject.fromObject(callbackMap).toString();
            respMap.put("callback",BinaryUtil.toBase64String(callback.getBytes()));
            JSONObject ja1 = JSONObject.fromObject(respMap);
            response.setHeader("Access-Control-Allow-Origin", "*");
            response.setHeader("Access-Control-Allow-Methods", "GET, POST");
            response.setContentType("text/html;charset=utf-8");
            AliyunOssUtils.response(request, response, ja1.toString(),HttpServletResponse.SC_OK);
            
        } catch (Exception e) {
        	 e.printStackTrace();
        }
    }
	
	
	/**
	 * 图片上传回调接收服务
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "ossimgcallback")
    public void ossimgcallback(HttpServletRequest request,HttpServletResponse response) { 
		String ossCallbackBody = null;
        boolean ret = false;
        try {
            int contentLength = Integer.parseInt(request.getHeader("content-length"));
            ossCallbackBody = AliyunOssUtils.getPostBody(request.getInputStream(), contentLength );
            ret = AliyunOssUtils.verifyOSSCallbackRequest(request, ossCallbackBody);
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            if (ret) {
            	Map<String, String> bodymap=AliyunOssUtils.URLParamToMap(ossCallbackBody);
            	String filepath=bodymap.get("filename");
            	int n=filepath.lastIndexOf("/");
            	String filename=filepath.substring(n+1);
            	n=filename.lastIndexOf(".");
            	//保存到数据库
            	JdataBean bean=new JdataBean();
 	            bean.put("filename", filename);
 	            bean.put("filetype", filename.substring(n+1));
 	            bean.put("filepath", filepath);
 	            bean.put("createtime",new Date());
 	            bean.put("viewpath", filepath);
 	            String fileid=UploadService.getIntance().addPhoto(bean);
 	            com.alibaba.fastjson.JSONObject rejson=new com.alibaba.fastjson.JSONObject();
 	            rejson.put("error", 0);
 	            rejson.put("fileid", fileid);
 	            rejson.put("url", UploadUtil.getConfig().getDownserver()+filepath);
 	            rejson.put("basepath", UploadUtil.getConfig().getDownserver());
 	            AliyunOssUtils.response(request, response, rejson.toString(), HttpServletResponse.SC_OK);
            } else {
            	AliyunOssUtils.response(request, response, "{\"error\":1,\"Status\":\"verdify not ok\"}", HttpServletResponse.SC_BAD_REQUEST);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
	
	@RequestMapping(value = "fileupload")
    public void fileupload(String updir,HttpServletRequest request,HttpServletResponse response) {
		OSSClient client = new OSSClient(AliyunOssConfig.getConfig().getEndpoint(), AliyunOssConfig.getConfig().getAccessId(), AliyunOssConfig.getConfig().getAccessSecret());
		com.alibaba.fastjson.JSONObject rejson=new com.alibaba.fastjson.JSONObject();
        rejson.put("error", 0);
        String dir=updir;if(dir==null)dir="";
		if(StringUtils.isNotBlank(dir) && !dir.endsWith("/"))dir+="/";
		try {
			boolean isMulti = ServletFileUpload.isMultipartContent(request);
			FileItemFactory fileItemFactory = new DiskFileItemFactory();
			ServletFileUpload upload = new ServletFileUpload(fileItemFactory);
			upload.setHeaderEncoding("utf-8");
			List<FileItem> items = upload.parseRequest(request);
			for (FileItem fileItem : items) {
				if (!fileItem.isFormField()) {
					String fname=fileItem.getName();
					int n=fname.lastIndexOf(".");
	                String type=fname.substring(n+1);
	            	Random rd=new Random();
	            	String newname=dir+DateConvert.toString(new Date(),"yyMMddHHmmssSSS")+rd.nextInt(99)+"."+type;
	            	
	            	PutObjectResult result =client.putObject(AliyunOssConfig.getConfig().getBucket(),newname, fileItem.getInputStream());
	            	//保存到数据库
	            	JdataBean bean=new JdataBean();
	 	            bean.put("filename", newname);
	 	            bean.put("filetype", type);
	 	            bean.put("filepath", newname);
	 	            bean.put("createtime",new Date());
	 	            bean.put("viewpath", newname);
	 	            String fileid=UploadService.getIntance().addPhoto(bean);
	            	rejson.put("error", 0);
	  	            rejson.put("fileid", fileid);
	  	            rejson.put("url", UploadUtil.getConfig().getDownserver()+newname);
	  	            rejson.put("basepath", UploadUtil.getConfig().getDownserver());
				}
			}
        } catch (Throwable e) {
            e.printStackTrace();
            rejson.put("error", 1);
        } finally {
            client.shutdown();
        }
		response.setContentType("text/html; charset=UTF-8");
		try {
			response.getWriter().print(rejson.toString());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
